import javax.sound.midi.*;

/**
 * MidiController
 * Handles Midi synthesis for client
 * @author James Varvaro
 */
public class MidiController {
    private Synthesizer synth = null;
    private Receiver synthRcvr = null;
    
    public MidiController() {
        try {
            synth = MidiSystem.getSynthesizer();
            synth.open();
            synthRcvr = synth.getReceiver();
            synth.loadAllInstruments(synth.getDefaultSoundbank());
        }
        catch(MidiUnavailableException ex) {
            System.err.println("Midi is unavailable. Sound will not work.");
        }
    }

    public int getInstNumber(String instrumentType) {
       int instrumentNumber = 4;
       
       if(instrumentType.equals("piano")) {
           instrumentNumber = 4;
        }
        else if(instrumentType.equals("steel drums")) {
            instrumentNumber = 115;
        }
        else if(instrumentType.equals("guitar")) {
            instrumentNumber = 28;
        }
        
        return instrumentNumber;
    }
    
    public void playNote(int noteid, String instrumentType, int pitch) {
        ShortMessage instChangeMsg = new ShortMessage();
       ShortMessage noteMsg = new ShortMessage();
       try {
            instChangeMsg.setMessage(ShortMessage.PROGRAM_CHANGE, 0, getInstNumber(instrumentType) ,0);
            noteMsg.setMessage(ShortMessage.NOTE_ON, 4, 60 + pitch, 93);
       }
       catch(InvalidMidiDataException ex) {
            System.err.println("Invalid midi message.");
       }
        
      // synthRcvr.send(instChangeMsg, -1);
      synth.getChannels()[4].programChange(getInstNumber(instrumentType));
        synthRcvr.send(noteMsg, -1);
    }
    
    public void stopNote(int noteid, String instrumentType, int pitch) {
       ShortMessage noteMsg = new ShortMessage();
       try {
            noteMsg.setMessage(ShortMessage.NOTE_OFF, 4, 60 + pitch, 93);
       }
       catch(InvalidMidiDataException ex) {
            System.err.println("Invalid midi message.");
       }
        
        synthRcvr.send(noteMsg, -1);
    }
}
